package svc

import (
	"backend/internal/config"
	"backend/internal/core/modbus_client"
	"backend/internal/db/model"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type ServiceContext struct {
	Config        config.Config
	GormDB        *gorm.DB                     // 添加 GORM 连接
	ClientManager *modbus_client.ClientManager // 添加 Modbus 客户端管理器
}

func NewServiceContext(c config.Config, clientManager *modbus_client.ClientManager) *ServiceContext {
	// 初始化 GORM
	db, err := gorm.Open(sqlite.Open(c.DataSource), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	// 自动迁移设备表（可选）
	err = db.AutoMigrate(&model.Device{})
	if err != nil {
		return nil
	}

	return &ServiceContext{
		Config:        c,
		GormDB:        db,
		ClientManager: clientManager,
	}
}
